﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vds2465Telegrams;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_35_GPSCoordinates
	{
		#region constants

		private const byte NrOfHeaderBytes = 2;

		#endregion constants

		#region internal methods

		internal static byte[] GenerateBytes(UserData userData)
		{
			byte[] userDataBytes = null;
			if (userData is UserData_35_GPSCoordinates)
			{
				UserData_35_GPSCoordinates userData35 = userData as UserData_35_GPSCoordinates;

				byte[] gpsBytes = userData35.GetCopyOfBytes();
				int nrOfBytes = 0;
				if (gpsBytes != null)
				{
					nrOfBytes = gpsBytes.Length;
				}
				byte nrOfTotalBytes = (byte)(NrOfHeaderBytes + nrOfBytes);

				userDataBytes = new byte[nrOfTotalBytes];
				userDataBytes[0] = (byte)(nrOfTotalBytes - GenParse_UserData.HeaderLength);	// user data length
				userDataBytes[1] = UserData.UserData35GPSCoordinates;
				if (gpsBytes != null)
				{
					for (int index = 0; index < gpsBytes.Length; index++)
					{
						userDataBytes[NrOfHeaderBytes + index] = gpsBytes.ElementAt(index);
					}
				}
			}
			else
			{
				// TODO handle error - wrong UserData type	
			}

			return userDataBytes;
		}

		internal static bool ParseBytes(byte[] userDataBytes, out UserData userData35GPSCoordinates, out int consumedBytes)
		{
			userData35GPSCoordinates = null;
			consumedBytes = 0;

			if (userDataBytes.Length >= NrOfHeaderBytes)
            {
				byte setLength = userDataBytes[0];
				if (userDataBytes.Length >= setLength + NrOfHeaderBytes)
				{
					if (userDataBytes[1] == UserData.UserData35GPSCoordinates)
					{
						byte nrOfGPSBytes = userDataBytes[0];
						byte[] gpsBytes = new byte[nrOfGPSBytes];
						for (int index = 0; index < nrOfGPSBytes; index++)
						{
							gpsBytes[index] = userDataBytes[NrOfHeaderBytes + index];
						}

						userData35GPSCoordinates = new UserData_35_GPSCoordinates(gpsBytes);
						consumedBytes = setLength + NrOfHeaderBytes;
						return true;
					}

					// TODO handle error: wrong value for the data type
					return false;
				}
				
				// TODO handle error: not enough bytes as specified by the SL value
				return false;
			}

			// TODO handle error (not enough header bytes)
			return false;
		}

		#endregion internal methods
	}
}
